package com.zyn.es.admin;

import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.health.ClusterIndexHealth;
import org.elasticsearch.common.unit.TimeValue;

import com.zyn.es.basic.EsClient;

/**
 * 集群管理
 * 
 * https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-admin-cluster.html
 * @author tongyufu
 *
 */
public class ClusterAdmin extends EsClient {

    public static void main(String[] args) {
        ClusterAdmin cluster = new ClusterAdmin();
        cluster.clusterHealth();
        cluster.waitStatus();
    }

    /**
     * 集群健康
     */
    public void clusterHealth() {
        super.initClient();
        log.info("================================");
        ClusterHealthResponse response = client.admin().cluster().prepareHealth().get();
        log.info("clusterName：" + response.getClusterName());
        log.info("numberOfDataNodes:" + response.getNumberOfDataNodes());
        log.info("numberOfNodes:" + response.getNumberOfNodes());

        for (ClusterIndexHealth health : response.getIndices().values()) {
            log.info("numberOfShards:" + health.getNumberOfShards());
            log.info("numberOfReplicas:" + health.getNumberOfReplicas());
            ClusterHealthStatus status = health.getStatus();
            log.info("status:" + status.toString());
        }
        log.info("================================");
        client.close();
    }

    /**
     * 监控集群状态
     */
    public void waitStatus() {
        super.initClient();
        log.info("================================");
        try {
            ClusterHealthResponse response = client.admin().cluster().prepareHealth()
                .setWaitForGreenStatus().setTimeout(TimeValue.timeValueSeconds(5)).get();
            ClusterHealthStatus status = response.getIndices().get(INDEX).getStatus();
            if (!status.equals(ClusterHealthStatus.GREEN)) {
                throw new RuntimeException("Index is in " + status + " state");
            }
            log.info("================================");
        } finally {
            client.close();
        }
    }
}
